package com.tongcao.cn.util;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author:tongcao
 * @since:2019/7/9 15:03
 * Description:
 */
public final class WebSocketUtils {

    /**
     * 模拟存储 websocket session 使用
     */
    public static final Map<String, Session> LIVING_SESSION_CACHE = new ConcurrentHashMap<>();

    /**
     * 群发消息
     *
     * @param message
     */
    public static void sendMessageAll(String message) {
        LIVING_SESSION_CACHE.forEach((sessionId, session) -> sendMessage(session, message));
    }


    /**
     * p2p(point to point )
     *
     * @param session
     * @param msg
     */
    public static void sendMessage(Session session, String msg) {
        if (session == null) {
            return;
        }

        final RemoteEndpoint.Basic basic = session.getBasicRemote();
        if (basic == null) {
            return;
        }
        try {
            basic.sendText(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}